const express = require('express');
const cors = require('cors');
const jwt = require('jsonwebtoken');
const url = require('url');
const UserRouter = require('./Router/UserRouter');
const BooksRouter = require('./Router/BooksRouter');
const BooksTypeRouter = require('./Router/BooksTypeRouter');
const AttachmentRouter = require('./Router/AttachmentRouter');
const sequelize = require('./config/database');

const app = express();
app.use(cors());

let primaryKey = '$#^%RXFE^%%%$*&(*#';

// 同步到数据库
sequelize.sync({ alter: true });

// 解析表单请求体 application/json
app.use(express.json());
// 解析表单请求体 application/x-www-form-urlencoded，extended: true 允许包含任何数据类型
app.use(express.urlencoded({ extended: true }));

// 托管静态资源(html、css、images、js..)
app.use('/uploads', express.static('./uploads'));

// 不需要校验token /login
const noNeedToken = ['/login', '/uploadpicture', '/getrefreshtoken'];
app.use((req, res, next) => {
  let pathname = url.parse(req.url, true).pathname.toLowerCase();
  console.log(pathname);
  let token = req.headers.authorization;
  if (!noNeedToken.includes(pathname)) {
    // 校验
    try {
      let userInfo = jwt.verify(token, primaryKey);
      // 校验成功 token => user_id
      req.userInfo = userInfo;
      next();
    } catch (err) {
      // 校验失败 401
      res.status(401).json({ message: '权限有误' });
    }
  } else {
    next();
  }
});

app.use('/', UserRouter);
app.use('/', BooksRouter);
app.use('/', BooksTypeRouter);
app.use('/', AttachmentRouter);

app.listen(5000, () => {
  console.log('server is running at port 5000');
});
